package com.sky.service.impl;

import com.alibaba.druid.support.json.JSONUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.constant.JwtClaimsConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.mapper.UserMapper;
import com.sky.properties.JwtProperties;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.JwtUtil;
import com.sky.vo.UserLoginVO;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    UserMapper userMapepr;

    @Autowired
    JwtProperties jwtProperties;

    @Autowired
    WeChatProperties weChatProperties;

    /**
     * 用户登录
     * @param userLoginDTO
     * @return
     */
    @Override
    public UserLoginVO login(UserLoginDTO userLoginDTO) throws IOException {

//获取openId
        //拼接请求路径
        String uri =
                "https://api.weixin.qq.com/sns/jscode2session?js_code="+userLoginDTO.getCode()
                +"&appid="+weChatProperties.getAppid()
                +"&secret="+weChatProperties.getSecret()
                +"&grant_type=authorization_code";

        //创建httpclient对象
        CloseableHttpClient httpClient= HttpClients.createDefault();

        //创建请求对象
        HttpGet httpGet = new HttpGet(uri);

        //发送请求，接受响应结果
        CloseableHttpResponse response = httpClient.execute(httpGet);

        HttpEntity entity = response.getEntity();
        String body = EntityUtils.toString(entity);
        JSONObject jsonObject = JSON.parseObject(body);
        String openId = jsonObject.getString("openid");

        response.close();
        httpClient.close();


//添加新用户，获取用户id
        UserLoginVO userLoginVO = new UserLoginVO();

        User user = userMapepr.find(openId);
        if (user == null) {
            userLoginVO.setOpenid(openId);
            userMapepr.add(userLoginVO);
        }else{
            userLoginVO.setId(user.getId());
        }


//生成jwt令牌
        Map<String,Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.USER_ID,userLoginVO.getId());
        String token=JwtUtil.createJWT(jwtProperties.getUserSecretKey(),jwtProperties.getUserTtl(),claims);

        userLoginVO.setToken(token);

        return userLoginVO;
    }
}
